import {Image, ScrollView, Video, Text, View} from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, {Component} from 'react';
import * as T from '../types';
import actions from '../actions/index';
import {connect} from 'react-redux';
import {store2Props} from '../selectors';
import api from 'api';
import 'taro-ui/dist/style/components/tabs.scss';
import './post.less';
import Blank from '@/pages/common/blank';
import {returnTime} from '@/utils/returnTime';
import userImg from '@/assets/image/community/user.png';
import write from '@/assets/image/community/write.png';
import zan from '@/assets/image/community/zan.png';
import zanCurr from '@/assets/image/community/zan-curr.png';
import share from '@/assets/image/community/share.png';
import nones from '@/assets/image/none/nones.png';
import Index from '../index';

type IPostProps = T.IProps & T.IPostProps;
//@ts-ignore
@connect<Partial<IPostProps>, T.IPostState>(store2Props, actions)
export default class post extends Component<Partial<IPostProps>, T.IPostState> {
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
      clickLikeVal: false,
      loadingList: false,
      end: false,
    };
  }

  componentDidMount() {}

  //详情
  navPostDetail(item, type) {
    Taro.navigateTo({
      url: `/pages/package-B/community-detail/index?id=${item.id}&type=${type}`,
    });
  }

  renderItem(list, type) {
    let {
      actions: {action},
    } = this.props;
    return (
      <View className="itemBox">
        {list.map((item, index) => (
          <View
            className="postViews"
            onClick={(e) => {
              e.stopPropagation();
              if (Taro.getStorageSync('blacklistModel')) {
                action.commonChange('main.blacklistModel', true);
                return;
              }
              this.navPostDetail(item, false);
            }}
            key={item.id}
          >
            {item.videoImg && item.videoUrl ? (
              <View
                className="imgItem"
                onClick={() => {
                  // this.setState({
                  //   videoAddress: item.videoUrl,
                  //   customVideoShow: true,
                  // });
                }}
              >
                <Video
                  className="video"
                  src={item.videoUrl}
                  initialTime={0}
                  controls
                  autoplay={false}
                  loop={false}
                  muted={false}
                />
              </View>
            ) : null}
            {item.url != '' && item.url ? this.renderImg(item.url.split(';')) : null}
            {item.content != '' && <Text className="title">{item.content}</Text>}
            <View className="userBox">
              <View className="row">
                <Image className="userImg" mode="aspectFill" src={item.userImg || userImg} />
                <View className="userName">{item.userName}</View>
              </View>
              <View
                className="row"
                onClick={(e) => {
                  e.stopPropagation();
                  if (Taro.getStorageSync('blacklistModel')) {
                    action.commonChange('main.blacklistModel', true);
                    return;
                  }
                  this.LikeClick(item, index, item.thumbFlag, type);
                }}
              >
                {item.thumbFlag ? (
                  <Image className="b_icon" mode="widthFix" src={zan} />
                ) : (
                  <Image className="b_icon" mode="widthFix" src={zanCurr} />
                )}
                <View className="thumbNum">{item.thumbNum}</View>
              </View>
            </View>
          </View>
        ))}
      </View>
    );
  }

  //图片渲染
  renderImg(list) {
    return (
      <View className="imgItem">
        <Image
          // onClick={this.onImageClick.bind(this, list[0], [list[0]])}
          src={list[0]}
          mode="widthFix"
          className="b_img"
        />
      </View>
    );
  }
  onImageClick = (item, urls) => {
    this.previewImage(item, urls);
  };
  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };

  //点赞、取消点赞
  async LikeClick(item, index, thumbFlag, type) {
    let {clickLikeVal} = this.state;
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (!itemStr) {
      Taro.navigateTo({
        url: '/pages/package-C/login/login/index',
      });
      return;
    } else {
      if (clickLikeVal) {
        return;
      }
      this.setState(
        {
          clickLikeVal: true,
        },
        () => {
          let {
            main: {leftData, rightData},
            actions: {action},
          } = this.props;
          if (thumbFlag) {
            //点赞后处理
            if (type == 1) {
              leftData[index].thumbFlag = !thumbFlag;
              leftData[index].thumbNum += 1;
              action.commonChange('main.leftData', leftData);
            } else {
              rightData[index].thumbFlag = !thumbFlag;
              rightData[index].thumbNum += 1;
              action.commonChange('main.rightData', rightData);
            }
          } else {
            //取消点赞后处理
            if (type == 1) {
              leftData[index].thumbFlag = !thumbFlag;
              leftData[index].thumbNum -= 1;
              action.commonChange('main.leftData', leftData);
            } else {
              rightData[index].thumbFlag = !thumbFlag;
              rightData[index].thumbNum -= 1;
              action.commonChange('main.rightData', rightData);
            }
          }
          let params = {
            userId: itemStr.user.id,
            targetId: item.id,
            type: 1,
          };
          if (thumbFlag) {
            //点赞
            action.addThumb(params);
          } else {
            //取消点赞
            action.deleteThumb(params);
          }
          this.setState({
            clickLikeVal: false,
          });
        },
      );
    }
  }

  _onScrollToLower = async () => {
    console.log('触发了', this.state.loadingList);
    if (this.state.loadingList) return;
    let {
      main: {pageNum, totalPages},
      actions: {action},
    } = this.props;
    let num = pageNum + 1;
    console.log(pageNum, totalPages, '我是两个');
    if (pageNum == totalPages) return;
    this.setState({
      loadingList: true,
    });
    this.props.actions.action.commonChange('main.pageNum', num);
    // this.props.actions.action.commonChange('main.totalPages', 0);

    // return
    const end = await this.props.actions.action.getPosts();
    // return
    this.setState({
      loadingList: false,
      end,
    });
  };

  _onRefresherRefresh = async () => {
    // if (this.state.loadingList) return;
    // this.setState({
    //   loadingList: true
    // })
    // console.log(flag)
    let {refresherTriggered} = this.state;
    this.setState({
      refresherTriggered: true,
    });
    if (refresherTriggered) return;

    this.props.actions.action.commonChange('main.totalPages', 0);
    this.props.actions.action.commonChange('main.pageNum', 1);
    const end = await this.props.actions.action.getPosts();
    // setTimeout(() => {
    this.setState({
      refresherTriggered: false,
      loadingList: false,
      end,
    });
    // }, 2000);
    // this.setState({
    //   loadingList: false
    // })
  };

  render() {
    let {refresherTriggered} = this.state;
    let {
      main: {leftData, rightData},
      // actions: { action },
    } = this.props;

    return (
      <View className="communityPost">
        {leftData.length > 0 && (
          <ScrollView
            className="scrollView"
            onScrollToLower={() => this._onScrollToLower()}
            refresherEnabled
            refresherTriggered={refresherTriggered}
            onRefresherRefresh={() => this._onRefresherRefresh()}
            scrollY
          >
            <View className="flex">
              {this.renderItem(leftData, 1)}
              {this.renderItem(rightData, 2)}
            </View>
            <View className="status">{this.state.loadingList ? '加载中' : this.state.end ? '已经到底了~' : ''}</View>

            {/* {leftData.length != 0 && pageNum != totalPages && <View className="status">加载中</View>} */}
            {/* {!isLoading && leftData.length != 0 && pageNum == totalPages && <View className="status">已经到底了~</View>} */}
          </ScrollView>
        )}

        {leftData.length <= 0 && (
          <Blank
            content="还没有帖子信息！"
            img={nones}
            imgStyle={{width: '343rpx', height: '288rpx'}}
            textStyle={{
              fontSize: '28rpx',
              color: '#BFBFBF',
              textAlign: 'center',
              marginTop: '40rpx',
            }}
          />
        )}
      </View>
    );
  }
}
